<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Purchase");
$page_title=__("Purchase");
$content_title=__("Purchase");

if($r_user['activated'] != 'y'){
	$errmsg = replace_tag(__("You cannot make any purchase since you have not activated your account yet. To activate your account, please click <%link%>here<%/link%>."), array("<%link%>"=>"<a href='".MEMBER_URL."/".$vars['file']['member']['activate']."'>", "<%/link%>"=>"</a>"));
	$content="<h2>$page_title</h2>".format_err($errmsg);
	print format_member_page($content, $this_title, $content_title);
	exit();
}
	
$r_payment_channel=array('e');
$r_payment_channel_d=array('e'=>__($vars['ewallet_title'])." ".$vars['currency'].number_format($r_user['ewallet'], 2));
//products
$t=@mysql_num_rows($r=mysql_query("select * from $db->products where status='active' order by title"));
for($i=0;$i<$t;$i++){
	$prod = mysql_fetch_assoc($r);
	$r_product[$i] = $prod['refno'];
	$r_product_d[$prod['refno']] = "Ref# $prod[refno], $prod[title] $vars[currency]".number_format($prod['price'], 2)." (".number_format($prod['bv'], 2)."BV)";
	$js_prod[$prod['refno']]['price'] = $prod['price'];
	$js_prod[$prod['refno']]['bv'] = $prod['bv'];
}
for($i=1;$i<=10;$i++){
 $r_qty[]=$i;
 $r_qty_d[$i]=$i;
}
//stockist list
$r_hq[0] = 'hq';
$r_hq[1] = 'cr';
$r_stockist = $r_hq;
$r_stockist_d['hq'] = __("Headquarter");
$r_stockist_d['cr'] = __("Courier");
$t=@mysql_num_rows($r=mysql_query("select * from $db->users where is_stockist='y' order by name")) or 0;
for($i=0;$i<$t;$i++){
	$st = mysql_fetch_assoc($r);
	$r_stockist[($i+2)] = $st['id'];
	$r_stockist_d[$st['id']] = "Stockist ID: ".$st['id'].", Name: ".$st['name'];
}

$td_width=180;

//#####PRODUCT POST#####
if($_POST["__req"]){
 if(!strlen($post_s["password"])){
  $errmsg.=replace_tag(__("'<%field%>' is a required field."), array("<%field%>"=>__("Password")))."<br />\n";
 }else{
  $enc_pass=explode(":", $r_user["enc_password"]);
  $salt=$enc_pass[1];
  if(md5($post_s["password"].$salt)!=$enc_pass[0]){
   $errmsg.=__("You have entered an invalid Password.")."<br />\n";
  }
 }
 $cost = $total_bv = 0;
 $purchase_descr = '';
 foreach($post_s as $f=>$v){
  if(preg_match('/^_refno_[0-9]+/', $f)){
   $index = preg_replace('/^_refno_/', '', $f);
   $refno = $v;
   $qty = $post_s["qty_$index"];
   if(!is_numeric($qty) || $qty<=0){
    $errmsg.=replace_tag(__("Please enter a valid quantity for the product '<%prod%>'."), array("<%prod%>"=>$r_product_d[$refno]))."<br />\n";
   }
   $cost += ($qty * $js_prod[$refno]['price']);
   $total_bv += ($qty * $js_prod[$refno]['bv']);
   $purchase_descr.=($purchase_descr? ", " : "").$r_product_d[$refno]." x ".$qty;
   $purchased_prods[$refno] = $qty;
  }
 }
 if(!count($purchased_prods)){
  $errmsg.=__("Please select a product to purchase.")."<br />\n";
 }
 //check collection location
 if(!$errmsg){
	if(!in_array($post_s['stockist'], $r_stockist)){
		$errmsg.=__("Please select a pickup location (Purchase From).")."<br />";
	}
 }
 if(!$errmsg){
  if($post_s['payment_channel']=='e' && $r_user['ewallet']<$cost){
   $errmsg.=replace_tag(__("You do not have sufficient <%title%> to purchase this product."), array("<%title%>"=>__($vars['ewallet_title'])))."<br />\n".replace_tag(__("<%title%> required: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($cost, 2)))."<br />\n".replace_tag(__("<%title%> available: <%x%>"), array("<%title%>"=>__($vars['ewallet_title']), "<%x%>"=>number_format($r_user['ewallet'], 2)))."<br />\n";
  }
 }

 if(!$errmsg){
  $datetime=ndate();
  if(!mysql_query($sql="update $db->users set ".($post_s['payment_channel']=='e'? "ewallet=ewallet" : "")."-$cost where id='$uid' limit 1")){
   $errmsg.=__("We have encountered some error while purchasing the product for you.")." ".__("You can try again later. If the problem persists, please contact us.")."<br />\n".($vars['debug']? "<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n" : "");
  }else{
   $purchase_descr2="Purchase of $purchase_descr";
   //insert ewallet record
   if(!mysql_query($sql="insert into ".($post_s['payment_channel']=='e'? $db->member_ewallet_record : '')." (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$cost', '".AddSlashes("Debited $vars[currency]".number_format($cost, 2)." for $purchase_descr2")."', '$datetime')")){
    $critical_error.="Error creating the member ".($post_s['payment_channel']=='e'? $vars['ewallet_title'] : '')." record when member ID #$uid make a purchase. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
   }
   //insert purchase record
   if(!mysql_query($sql="insert into $db->purchase (uid, sid, stockist_sale, mail_type, amount, total_bv, payment_channel, first_sale, status, cdate) values ('$uid', '".(!in_array($post_s['stockist'], $r_hq)? $post_d['stockist'] : '0')."', '".(!in_array($post_s['stockist'], $r_hq)? 'y' : 'n')."', '".(in_array($post_s['stockist'], $r_hq)? $post_d['stockist'] : '')."', '$cost', '$total_bv', '$post_d[payment_channel]', 'n', 'confirmed', '$datetime')")){
    $critical_error.="Error creating the member purchase record when member ID #$uid make a purchase. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
    $pid="0";
   }else{
    $pid=mysql_insert_id();
    //insert sales detail
    foreach($purchased_prods as $refno => $qty){
     $this_cost=$js_prod[$refno]['price'] * $qty;
     $this_bv=$js_prod[$refno]['bv'] * $qty;
     if(!mysql_query($sql="insert into $db->purchase_detail (pid, product_code, product_name, qty, amount, bv, total, total_bv) values ('$pid', '".AddSlashes($refno)."', '".AddSlashes($r_product_d[$refno])."', '$qty', '".$js_prod[$refno]['price']."', '".$js_prod[$refno]['bv']."', '$this_cost', '$this_bv')")){
      $critical_error.="Error creating the member sales detail when member ID #$uid make a purchase. Please manually execute the SQL below to record the sales detail.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
     }
    }
   }
   //credit commission to upline, if this is the first sale
   if($first_sale){//1st sale
    $total_level=1;
    $level=1;
    $upline_id=$r_user['ref'];
    while($upline_id && $level<=$total_level){
     $r_upline=get_user_detail_by_id($upline_id);
     //upline only can receive comm if activated
     if(1){//$r_upline['activated']=='y'){
      $percent=$vars['product_ref_comm'];
      $comm_amount=round($total_bv * $percent / 100, 2);
      //create comm record
      if(!mysql_query($sql="insert into $db->member_comm (cid, uid, from_uid, type, amount, percent, level, year, month, day, status, cdate) values ('$pid', '$upline_id', '$uid', 'r', '$comm_amount', '$percent', '$level', '".ndate('Y')."', '".ndate('n')."', '".ndate('j')."', 'confirmed', '$datetime')")){
       $critical_error.="Error creating the commission record for sponsor ID #$upline_id (level $level) when member ID #$uid make a purchase. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
      }
      /*/credit to upline
      if(!mysql_query($sql="update $db->users set ewallet=ewallet+$comm_amount where id='$upline_id'")){
       $critical_error.="Error crediting the commission to sponsor ID #$upline_id (level $level) when member ID #$uid make a purchase.<br />\n<br />\n$vars[ewallet_title]: $comm_amount<br />\n<br />\nPlease manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
      }
      //record ewallet record
      if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$upline_id', 'credit', '$comm_amount', '".AddSlashes("Credited $vars[currency]".number_format($comm_amount, 2)." for sponsor commission received when referral ID #$uid (level $level) make a purchase.")."', '$datetime')")){
       $critical_error.="Error creating the $vars[ewallet_title] record for sponsor commission received for sponsor ID #$upline_id (level $level) when member ID #$uid make a purchase. Please manually execute the SQL below to record the transaction:<br />\n<br />\n$sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
      }*/
     }
     if($r_upline['ref']){
      $upline_id=$r_upline['ref'];
     }else{
      unset($upline_id);
     }
     $level++;
    }
   }
  }

  if(!$errmsg){
   $msg=replace_tag(__("Your have successfully purchased '<%product%>'."), array("<%product%>"=>$purchase_descr))."<br />\n";
   $r_user=get_user_detail_by_id($uid);
   $r_payment_channel_d=array('e'=>__($vars['ewallet_title'])." ".$vars['currency'].number_format($r_user['ewallet'], 2));
  }
 }

 if($critical_error){
  $a_sub="$vars[title] - Purchase Failure for Member ID #$uid";
  $a_msg="
  <p>Dear admin,</p>
  <p>There was some error(s) while member ID #$uid make a purchase. The error is as follow:</p>
  $critical_error";
  email_admin($a_sub, $a_msg, 'e');
 }

 $msg=$msg? format_msg($msg) : "";
 $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}

$dis['payment_channel']=$post_s['__req']? $post_s['payment_channel'] : 'e';
$dis['product']=$post_s['__req']? $post_s['product'] : '';
$payment_channel_select=build_select($r_payment_channel, $r_payment_channel_d, $dis['payment_channel'], 'payment_channel', $inputbox_style);
$product_select=build_select($r_product, $r_product_d, $dis['product'], 'product', "style='width:90%;'");
$stockist_select=build_select($r_stockist, $r_stockist_d, $dis['stockist'], 'stockist', $inputbox_style);

//prod list
$prod_index = 0;
if($post_s['__req']){
 if(count($purchased_prods)){
  foreach($purchased_prods as $refno=>$qty){
   $prod_list.="<div id=\"prod_row_$prod_index\" name=\"prod_$refno\" class=\"prod_row\">".
     "<div class=\"delete_prod\"><a href=\"#\" name=\"delete_prod\" rel=\"$prod_index\"><img src=\"".M_URL."/images/icons/delete.png\" /></a></div><div class='prod_sep'></div>".
     "<div class=\"prod_refno\"><input type=\"text\" name=\"_prodname_$prod_index\" class=\"inputbox\" readonly=\"readonly\" value=\"".nhtmlentities($r_product_d[$refno])."\" style=\"width:".(USER_BROWSER=='msie'? '244' : '246')."px;\" />".
           "<input type=\"hidden\" name=\"_refno_$prod_index\" value=\"$refno\" /></div><div class='prod_sep'></div>".
     "<div class=\"prod_qty\"><input type=\"text\" name=\"qty_$prod_index\" class=\"inputbox\" value=\"$qty\" style=\"width:".(USER_BROWSER=='msie'? '116' : '118')."px;\" /></div>".
    "</div>";
   $prod_index++;
   $purchased_prod_js.="purchased_prod['".AddSlashes($refno)."'] = 1;\n";
  }
 }
}

//javascript
foreach($js_prod as $refno=>$details){
 $prod_price_js.="prod_price['".AddSlashes($refno)."'] = $details[price];\n";
 $prod_bv_js.="prod_bv['".AddSlashes($refno)."'] = $details[bv];\n";
 $prod_details_js.="prod_detail['".AddSlashes($refno)."'] = '".AddSlashes($r_product_d[$refno])."';\n";
}
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.livequery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 var prod_index = $prod_index;
 var purchased_prod = new Array();
 $purchased_prod_js
 var prod_price = new Array();
 $prod_price_js
 var prod_bv = new Array();
 $prod_bv_js
 var prod_detail = new Array();
 $prod_details_js

 j('form[@name=invest_form]').submit(function(){
  var pack='';
  var total_price = 0;
  var total_bv = 0;
  for(prefno in purchased_prod){
   if(purchased_prod[prefno] == 1){
    this_qty = j('div[@name=prod_'+prefno+']>div.prod_qty>input[@name^=qty_]').val();
    total_price += (this_qty * prod_price[prefno]);
    total_bv += (this_qty * prod_bv[prefno]);
    pack += prod_detail[prefno]+' x '+this_qty+'\\n';
   }
  }
  if(confirm('".AddSlashes(__("Purchase for")).":\\n\\n'+pack+'\\n".AddSlashes(("Total Price")).": '+total_price+'\\n".AddSlashes(("Total BV")).": '+total_bv+'\\n\\n".AddSlashes(__("Are you sure?"))."')){
   j('input[@name=submit_btn]').attr('disabled','disabled');
  }else{
   return false;
  }
 });".

 /*add new product*/"
 j('a[@name=add_prod]').click(function(){
  prod_refno = j('select[@name=product]>option:selected').val();
  prod_title = j('select[@name=product]>option:selected').text();
  if(j('div[@name=prod_'+prod_refno+']').length>0){
   qty = j('div[@name=prod_'+prod_refno+']>div.prod_qty>input[@name^=qty_]').val();
   j('div[@name=prod_'+prod_refno+']>div.prod_qty>input[@name^=qty_]').val(++qty);
  }else{
   j('div#prod_entry').append('".
    "<div id=\"prod_row_'+prod_index+'\" name=\"prod_'+prod_refno+'\" class=\"prod_row\">".
     "<div class=\"delete_prod\"><a href=\"#\" name=\"delete_prod\" rel=\"'+prod_index+'\"><img src=\"".M_URL."/images/icons/delete.png\" /></a></div><div class=\"prod_sep\"></div>".
     "<div class=\"prod_refno\"><input type=\"text\" name=\"_prodname_'+prod_index+'\" class=\"inputbox\" readonly=\"readonly\" value=\"'+prod_title+'\" style=\"width:".(USER_BROWSER=='msie'? '244' : '246')."px;\" />".
           "<input type=\"hidden\" name=\"_refno_'+prod_index+'\" value=\"'+prod_refno+'\" /></div><div class=\"prod_sep\"></div>".
     "<div class=\"prod_qty\"><input type=\"text\" name=\"qty_'+prod_index+'\" class=\"inputbox\" value=\"1\" style=\"width:".(USER_BROWSER=='msie'? '116' : '118')."px;\" /></div>".
    "</div>');
   purchased_prod[prod_refno] = 1;
   prod_index++;
  }

  return false;
 });".

 /*delete a product*/"
 j('a[@name=delete_prod]').livequery('click', function(){
  var id = j(this).attr('rel');
  var del_refno = j(this).parent().parent().attr('name').replace(/prod_/, '');
  purchased_prod[del_refno] = 0;
  j('div#prod_row_'+id).remove();
  return false;
 });
});
</script>";

//purchase form
$purchase=($errmsg || $msg? $errmsg.$msg : "").
"<p>".__("You can make your purchase here.")."</p>
<form name='invest_form' method='post' action='$this_file'>
<input type='hidden' name='__req' value='1' />
<table class='pbt_table'>
 <tr>
  <td width='$td_width'>".__("Product").__(":")." ".__("*")."</td>
  <td>$product_select <a href='#' name='add_prod'>".__("Add")."</a><br />\n<br />\n
      <div class='delete_prod'></div><div class='prod_sep'></div>
      <div class='prod_refno prod_title'>".__("Product")."</div><div class='prod_sep'></div>
      <div class='prod_qty prod_title'>".__("Quantity")."</div><div class='clear'></div>
      <div id='prod_entry'>$prod_list</div></td>
 </tr>
 <tr>
  <td width='$td_width'>".__("Purchase From").__(":")." ".__("*")."</td>
  <td>$stockist_select</td>
 </tr>
 <tr>
  <td width='$td_width'>".__("Payment Channel").__(":")." ".__("*")."</td>
  <td>$payment_channel_select</td>
 </tr>
 <tr>
  <td width='$td_width'>".__("Password").__(":")." ".__("*")."</td>
  <td><input type='password' name='password' style='width:399px;' /></td>
 </tr>
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='submit' name='submit_btn' value=\"".__("Submit")."\" />
  </td>
 </tr>
</table>
</form>";

$css=
"<style type='text/css'>
div.st_label{
 width:100px;
 float:left;
}
div.st_field{
 width:300px;
 height:25px;
 float:left;
}
div.delete_prod{
 width:20px;
 height:20px;
 float:left;
}
div.prod_refno{
 width:250px;
 border:0px solid #000;
 line-height:20px;
 height:20px;
 text-align:center;
 float:left;
 padding-left:0px;
}
div.prod_qty{
 width:122px;
 line-height:20px;
 height:20px;
 text-align:center;
 float:left;
}
div.prod_sep{
 float:left;
 width:5px;
 height:10px;
 background:none;
}
div.prod_title{
 background: #1E195C;
 color: #fff;
 font-weight:bold;
}
div.prod_row{
 height:20px;
 margin-top:3px;
}
</style>";

$content="<h2>$page_title</h2>".$purchase;
print format_member_page($content, $this_title, $content_title, $css.$jvscript);
?>